#! /bin/bash -e

#####################################################################
#                                                                   #
#               Compiles Faust programs to alsa-qt                  #
#               (c) Grame, 2009-2019                                #
#                                                                   #
#####################################################################

. faustpath
. faustoptflags
. usage.sh

CXXFLAGS+=" $MYGCCFLAGS"  # So that additional CXXFLAGS can be used

ARCHFILE=$FAUSTARCH/alsa-qt.cpp
ARCHLIB="-lasound"
POLY="POLY"
NVOICES=-1
EFFECT=""
SOUNDFILE="0"
SOUNDFILEDEFS=""
SOUNDFILEINC=""
SOUNDFILELIBS=""

if [[ $(uname -s) != Darwin ]]; then
    LFLAGS+="-no-pie"
fi

#-------------------------------------------------------------------------------
# Search for qmake or qmake-qt4

QMAKE=$(which qmake-qt4 || echo qmake)

#-------------------------------------------------------------------
# Analyze command arguments :
# faust options                 -> OPTIONS
# if -omp : -openmp or -fopenmp -> OPENMP
# existing *.dsp files          -> FILES
#

OSCINC=""
QTDEFS=""
OSCLIB=""

echoHelp()
{
    usage faust2alqt "[options] [Faust options] <file.dsp>"
    platform Linux
    require Alsa, QT
    echo "Compiles Faust programs to ALSA and QT"
    option
    options -httpd -osc -midi -qrcode -soundfile
    option "-nvoices <num>"
    option "-effect <effect.dsp>"
    option "-effect auto"
    option "Faust options"
    exit
}

if [ "$#" -eq 0 ]; then
    echo 'Please, provide a Faust file to process !'
    echo ''
    echoHelp
fi

# dispatch command arguments
while [ $1 ]
do
    p=$1

    if [ $p = "-help" ] || [ $p = "-h" ]; then
        echoHelp
    elif [ $p = "-nvoices" ]; then
        POLYDEFS="DEFINES += POLY"
        shift
        NVOICES=$1
        if [ $NVOICES -ge 0 ]; then
            CXXFLAGS="$CXXFLAGS -DNVOICES=$NVOICES"
        fi
    elif [ $p = "-effect" ]; then
        POLYDEFS="DEFINES += POLY2"
        POLY="POLY2"
        shift
        EFFECT=$1
    elif [ $p = "-soundfile" ]; then
        SOUNDFILE="1"
        SOUNDFILEDEFS="DEFINES += SOUNDFILE"
        SOUNDFILEINC=$(pkg-config --cflags sndfile | cut -c 3-)
        SOUNDFILELIBS=`pkg-config --static --libs sndfile`
    elif [ $p = "-midi" ]; then
        MIDIDEFS="DEFINES += MIDICTRL"
    elif [ $p = "-osc" ]; then
         OSCDEFS="DEFINES += OSCCTRL"
         OSCLIBS="-lOSCFaust"
    elif [ "$p" = "-httpd" ]; then
        HTTPDEFS="DEFINES += HTTPCTRL"
        HTTPLIBS="-lHTTPDFaust"
        HTTPLIBS1=`pkg-config --cflags --libs libmicrohttpd`
    elif [ "$p" = "-qrcode" ]; then # requires -httpd
        QRDEFS="DEFINES += QRCODECTRL"
    elif [ ${p:0:1} = "-" ]; then
        OPTIONS="$OPTIONS $p"
    elif [[ -f "$p" ]] && [ ${p: -4} == ".dsp" ]; then
        FILES="$FILES $p"
    else
        OPTIONS="$OPTIONS $p"
    fi

shift

done

#-------------------------------------------------------------------
# Check darwin specifics
#
if [[ $(uname) == Darwin ]]; then
    SPEC="-spec macx-g++"
    EXT=".app"
fi

#-------------------------------------------------------------------
# compile the *.dsp files
#
for p in $FILES; do

    CUR=$(pwd)
    f=$(basename "$p")
    SRCDIR=$(dirname "$p")

    # creates a temporary dir
    TDR=$(mktemp -d faust.XXXXXX)
    TMP="$TDR/${f%.dsp}"
    mkdir "$TMP"

    # compile faust to c++
    if [ $POLY = "POLY2" ]; then
        if [ $EFFECT = "auto" ]; then
            cat > effect.dsp << EndOfCode
            adapt(1,1) = _;
            adapt(2,2) = _,_;
            adapt(1,2) = _ <: _,_;
            adapt(2,1) = _,_ :> _;
            adaptor(F,G) = adapt(outputs(F),inputs(G));
            process = adaptor(library("$SRCDIR/$f").process, library("$SRCDIR/$f").effect) : library("$SRCDIR/$f").effect;
EndOfCode
            faust -i -json -a $ARCHFILE $OPTIONS "$SRCDIR/$f" -o "$TMP/${f%.dsp}.cpp" || exit
            faust -i -cn effect -a minimal-effect.cpp effect.dsp -o effect.h || exit
            rm effect.dsp
        else
            faust -i -json -a $ARCHFILE $OPTIONS "$SRCDIR/$f" -o "$TMP/${f%.dsp}.cpp" || exit
            faust -i -cn effect -a minimal-effect.cpp "$EFFECT" -o "effect.h" || exit
        fi
    else
        faust -i -a $ARCHFILE $OPTIONS "$SRCDIR/$f" -o "$TMP/${f%.dsp}.cpp" || exit
    fi

    # compile c++ to binary
    (
        cd "$TMP"
        $QMAKE -project "QT += widgets printsupport network" "INCLUDEPATH+=$CUR" "INCLUDEPATH+=$FAUSTINC" "INCLUDEPATH+=$SOUNDFILEINC" "QMAKE_CXXFLAGS=$CXXFLAGS -Wno-unused-parameter $FAUSTTOOLSFLAGS" "QMAKE_LFLAGS=$LFLAGS" "LIBS+=$ARCHLIB $SOUNDFILELIBS $OSCLIBS $HTTPLIBS $HTTPLIBS1" "HEADERS+=$FAUSTINC/faust/gui/QTUI.h" "RESOURCES+= $FAUSTINC/faust/gui/Styles/Grey.qrc" "$OSCDEFS" "$HTTPDEFS" "$QRDEFS" "$POLYDEFS" "$MIDIDEFS" "$SOUNDFILEDEFS"
        $QMAKE $SPEC QMAKE_CFLAGS_ISYSTEM=-I
        make
    ) > /dev/null || exit

    rm -rf "$SRCDIR/${f%.dsp}$EXT"
    cp -r "$TMP/${f%.dsp}$EXT" "$SRCDIR/${f%.dsp}$EXT"
    rm -rf "$TDR"
    rm -f effect.h "$f.json" "$SRCDIR/$f.json"

    # collect binary file name for FaustGIDE
    BINARIES="$BINARIES$SRCDIR/${f%.dsp}$EXT;"
done

echo $BINARIES
